package cn.dubito.manager.controller;

import cn.dubito.entity.Product;
import cn.dubito.manager.service.ProductService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;


/**
 * @author liliang
 * @description:
 * @date 2018/5/24.
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    private static Logger LOG = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private ProductService service;

    @ApiOperation(value = "创建产品", notes = "根据对应的业务规则添加产品")
    @PostMapping("")
    public Product addProduct(@RequestBody Product product) {
        LOG.info("创建产品参数: {}", product);
        Product result = service.addProduct(product);
        LOG.info("创建产品,返回结果: {}", result);
        return result;
    }

    @GetMapping("/{id}")
    public Product findProduct(@PathVariable("id") String id) {
        LOG.info("查询单个产品参数: {}", id);
        Product result = service.findProduct(id);
        LOG.info("查询单个产品,返回结果: {}", result);
        return result;
    }

    @GetMapping("")
    public Page<Product> query(String ids,
                               BigDecimal minRewardRate,
                               BigDecimal maxRewardRate,
                               String status,
                               @RequestParam(defaultValue = "0") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
        LOG.info("查询产品,ids={},minRewardRate={},maxRewardRate={},status={},pageNum={},pageSize={}",
                ids, minRewardRate, maxRewardRate, status, pageNum, pageSize);
        List<String> idList = null;
        List<String> statusList = null;
        if (!StringUtils.isEmpty(ids)) {
            idList = Arrays.asList(ids.split(","));
        }
        if (!StringUtils.isEmpty(status)) {
            statusList = Arrays.asList(status.split(","));
        }

        Pageable pageable = new PageRequest(pageNum, pageSize);
        Page<Product> query = service.query(idList, minRewardRate, maxRewardRate, statusList, pageable);
        LOG.info("查询产品返回结果:query={}", query);
        return query;
    }
}
